"""
CLAUDE.md Template Engine

Generates CLAUDE.md configurations from structured configuration data.
"""

from typing import Dict, List, Any, Optional
from datetime import datetime


class TemplateEngine:
    """
    Generate CLAUDE.md files from configuration dictionaries.
    
    This engine converts structured configuration data into properly
    formatted CLAUDE.md files that follow the Claude Code standards.
    """
    
    def __init__(self):
        """Initialize the template engine with predefined templates."""
        self.base_template = self._load_base_template()
        
    def generate_claude_md(self, config: Dict[str, Any]) -> str:
        """
        Generate a complete CLAUDE.md file from configuration.
        
        Args:
            config: Configuration dictionary containing all settings
            
        Returns:
            Complete CLAUDE.md content as string
        """
        sections = []
        
        # Header
        sections.append(self._generate_header(config))
        
        # Performance Configuration
        sections.append(self._generate_performance_config(config))
        
        # Primary Objectives
        sections.append(self._generate_objectives(config))
        
        # Execution Rules
        sections.append(self._generate_execution_rules(config))
        
        # Workflow
        sections.append(self._generate_workflow(config))
        
        # Agent Configuration
        sections.append(self._generate_agent_config(config))
        
        # Success Metrics
        sections.append(self._generate_success_metrics(config))
        
        # Additional Sections
        if "mle_star_config" in config:
            sections.append(self._generate_mle_star_section(config))
        
        if "agent_coordination" in config:
            sections.append(self._generate_coordination_section(config))
        
        return "\n\n".join(sections)
    
    def _generate_header(self, config: Dict[str, Any]) -> str:
        """Generate the header section."""
        use_case = config.get("use_case", "development").replace("_", " ").title()
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
        
        return f"""# CLAUDE.md - Optimized for {use_case}

<!-- Generated by CLAUDE.md Optimizer at {timestamp} -->

## 🎯 Configuration Overview
- **Use Case**: {use_case}
- **Optimization Target**: {config.get('optimization_priority', 'balanced')}
- **Team Size**: {config.get('team_size', 'N/A')}
- **Complexity**: {config.get('complexity', 'medium')}"""
    
    def _generate_performance_config(self, config: Dict[str, Any]) -> str:
        """Generate the performance configuration section."""
        max_agents = config.get("max_agents", 5)
        topology = config.get("swarm_topology", "hierarchical")
        
        perf_hints = config.get("performance_hints", {})
        
        section = f"""## ⚡ Performance Configuration
- **Execution Mode**: {self._get_execution_mode(perf_hints)}
- **Agent Count**: {max_agents} ({', '.join(config.get('preferred_agents', []))})
- **Topology**: {topology.title()}
- **Batch Operations**: {'MANDATORY' if perf_hints.get('batch_endpoints') else 'RECOMMENDED'}
- **Parallel Execution**: {'AGGRESSIVE' if perf_hints.get('aggressive_concurrency') else 'STANDARD'}"""
        
        if perf_hints:
            section += "\n- **Optimizations**:"
            for hint, enabled in perf_hints.items():
                if enabled:
                    section += f"\n  - {hint.replace('_', ' ').title()}"
        
        return section
    
    def _generate_objectives(self, config: Dict[str, Any]) -> str:
        """Generate the primary objectives section."""
        focus_areas = config.get("focus_areas", [])
        
        section = "## 🎯 Primary Objectives"
        
        if focus_areas:
            for i, area in enumerate(focus_areas, 1):
                section += f"\n{i}. {area}"
        
        # Add use-case specific objectives
        use_case = config.get("use_case", "")
        if use_case == "api_development":
            section += "\n4. Achieve <100ms response time for all endpoints"
            section += "\n5. Maintain 95% test coverage"
            section += "\n6. Generate 100% OpenAPI documentation coverage"
        elif use_case == "ml_pipeline":
            section += "\n4. Implement ensemble learning with MLE-STAR"
            section += "\n5. Achieve >90% model accuracy"
            section += "\n6. Optimize training time <30 minutes"
        elif use_case == "performance_optimization":
            section += "\n4. Identify and resolve performance bottlenecks"
            section += "\n5. Implement performance budgets and monitoring"
            section += "\n6. Achieve target performance metrics"
        
        return section
    
    def _generate_execution_rules(self, config: Dict[str, Any]) -> str:
        """Generate the execution rules section."""
        critical_rules = config.get("critical_rules", [])
        preferred_agents = config.get("preferred_agents", [])
        tool_priorities = config.get("tool_priorities", ["MultiEdit", "Edit", "Bash"])
        
        section = """## 🚀 Execution Rules

### CRITICAL: Concurrency Requirements
```javascript
// ALWAYS execute in single message:
["""
        
        # Add agent spawning pattern
        for i, agent in enumerate(preferred_agents[:4]):  # Limit to 4 for readability
            section += f'\n  Task("{agent.replace("-", " ").title()}", "...", "{agent}"),'
        
        section += '\n  TodoWrite({ todos: [ALL_TASKS] }),'
        section += '\n  // ... all related operations'
        section += '\n]'
        section += '```'
        
        # Add critical rules
        if critical_rules:
            section += "\n\n### Critical Rules"
            for rule in critical_rules:
                section += f"\n- {rule}"
        
        # Add tool priorities
        section += f"\n\n### Tool Priority Order\n1. {' → '.join(tool_priorities)}"
        
        return section
    
    def _generate_workflow(self, config: Dict[str, Any]) -> str:
        """Generate workflow section based on use case."""
        use_case = config.get("use_case", "")
        
        workflows = {
            "api_development": [
                "**Design Phase**: Create OpenAPI spec first",
                "**Implementation**: Use MultiEdit for endpoint creation", 
                "**Testing**: Parallel test execution",
                "**Documentation**: Auto-generate from OpenAPI",
                "**Optimization**: Profile and optimize slow endpoints"
            ],
            "ml_pipeline": [
                "**Data Preprocessing**: Batch data validation and cleaning",
                "**Feature Engineering**: Parallel feature extraction",
                "**Model Training**: MLE-STAR ensemble coordination",
                "**Evaluation**: Cross-validation with multiple metrics",
                "**Deployment**: Automated model versioning and deployment"
            ],
            "frontend_react": [
                "**Component Design**: Create reusable component library",
                "**State Management**: Implement centralized state",
                "**Testing**: Component and integration testing",
                "**Optimization**: Bundle size and performance optimization",
                "**Deployment**: Automated build and deployment"
            ],
            "testing_automation": [
                "**Test Planning**: Comprehensive test strategy",
                "**Implementation**: Parallel test creation",
                "**Execution**: Distributed test execution",
                "**Reporting**: Automated test reporting",
                "**Maintenance**: Continuous test optimization"
            ]
        }
        
        workflow_steps = workflows.get(use_case, [
            "**Planning**: Analyze requirements and plan approach",
            "**Implementation**: Execute development with parallel agents",
            "**Testing**: Comprehensive testing and validation",
            "**Documentation**: Generate comprehensive documentation",
            "**Optimization**: Performance analysis and optimization"
        ])
        
        section = f"### {use_case.replace('_', ' ').title()} Workflow"
        for step in workflow_steps:
            section += f"\n{step}"
        
        return section
    
    def _generate_agent_config(self, config: Dict[str, Any]) -> str:
        """Generate agent configuration section."""
        preferred_agents = config.get("preferred_agents", [])
        max_agents = config.get("max_agents", 5)
        topology = config.get("swarm_topology", "hierarchical")
        
        section = f"""## 🤖 Agent Configuration
- **Swarm Topology**: {topology.title()}
- **Maximum Agents**: {max_agents}
- **Preferred Agent Types**: {', '.join(preferred_agents)}"""
        
        # Add agent coordination if present
        coordination = config.get("agent_coordination", {})
        if coordination:
            section += "\n\n### Coordination Features"
            for feature, enabled in coordination.items():
                if enabled:
                    section += f"\n- {feature.replace('_', ' ').title()}: Enabled"
        
        return section
    
    def _generate_success_metrics(self, config: Dict[str, Any]) -> str:
        """Generate success metrics section."""
        use_case = config.get("use_case", "")
        
        metrics = {
            "api_development": [
                "Response Time: <100ms (p95)",
                "Test Coverage: >95%", 
                "Documentation: 100% coverage",
                "Error Rate: <0.1%"
            ],
            "ml_pipeline": [
                "Model Accuracy: >90%",
                "Training Time: <30 min",
                "Memory Usage: <8GB",
                "Ensemble Consensus: >95%"
            ],
            "performance_optimization": [
                "Performance Score: >0.9",
                "Bottleneck Resolution: 100%",
                "Memory Optimization: >20%",
                "Execution Time: <50% of baseline"
            ],
            "testing_automation": [
                "Test Coverage: >95%",
                "Test Execution Time: <5 min",
                "Test Success Rate: >99%",
                "Maintenance Overhead: <10%"
            ]
        }
        
        section = "## 📊 Success Metrics"
        success_metrics = metrics.get(use_case, [
            "Task Completion: >95%",
            "Error Rate: <5%",
            "Execution Time: Within targets",
            "Quality Score: >0.9"
        ])
        
        for metric in success_metrics:
            section += f"\n- {metric}"
        
        return section
    
    def _generate_mle_star_section(self, config: Dict[str, Any]) -> str:
        """Generate MLE-STAR specific configuration."""
        mle_config = config.get("mle_star_config", {})
        
        ensemble_size = mle_config.get("ensemble_size", 5)
        voting_strategy = mle_config.get("voting_strategy", "weighted")
        diversity = mle_config.get("model_diversity", "medium")
        
        section = f"""## 🧠 MLE-STAR Configuration
- **Ensemble Size**: {ensemble_size} models
- **Voting Strategy**: {voting_strategy.title()} consensus  
- **Model Diversity**: {diversity.title()}

### Ensemble Coordination Pattern
```python
# Initialize MLE-STAR ensemble
mcp__claude-flow__swarm_init({{
  topology: "mesh",
  maxAgents: 8,
  mle_star: {{
    enabled: true,
    models: ["model1", "model2", "model3", "model4", "model5"],
    consensus: "{voting_strategy}_voting"
  }}
}})

# Spawn ML agents in parallel
[
  Task("Data Preprocessing", "...", "ml-developer"),
  Task("Feature Engineering", "...", "ml-developer"), 
  Task("Model Training", "...", "ml-developer"),
  Task("Hyperparameter Tuning", "...", "optimizer"),
  Task("Model Evaluation", "...", "tester")
]
```"""
        
        return section
    
    def _generate_coordination_section(self, config: Dict[str, Any]) -> str:
        """Generate agent coordination section."""
        coordination = config.get("agent_coordination", {})
        
        section = "## 🔄 Agent Coordination Protocol"
        
        if coordination.get("pre_task_hooks"):
            section += """
### Pre-Task Initialization
```bash
npx claude-flow@alpha hooks pre-task --description "[task]"
npx claude-flow@alpha hooks session-restore --session-id "swarm-[id]"
```"""
        
        if coordination.get("post_edit_memory"):
            section += """
### Post-Edit Memory Sync
```bash
npx claude-flow@alpha hooks post-edit --file "[file]" --memory-key "swarm/[agent]/[step]"
npx claude-flow@alpha hooks notify --message "[decision]"
```"""
        
        if coordination.get("performance_analysis"):
            section += """
### Performance Analysis
```bash
npx claude-flow@alpha hooks post-task --task-id "[task]" --analyze-performance true
npx claude-flow@alpha hooks session-end --export-metrics true
```"""
        
        return section
    
    def _get_execution_mode(self, hints: Dict[str, Any]) -> str:
        """Determine execution mode from performance hints."""
        if hints.get("aggressive_concurrency"):
            return "Parallel-first (Aggressive)"
        elif hints.get("batch_processing"):
            return "Batch-optimized"
        elif hints.get("distributed_training"):
            return "Distributed"
        else:
            return "Standard"
    
    def _load_base_template(self) -> str:
        """Load the base template structure."""
        return """# CLAUDE.md - Configuration Template

This is the base template structure for CLAUDE.md configurations.
It will be populated with specific values for each use case.
"""


class UseCaseTemplates:
    """
    Pre-defined templates for common use cases.
    
    These templates provide starting points for specific development
    scenarios and can be customized further by the optimizer.
    """
    
    @staticmethod
    def get_api_development_template() -> str:
        """Get template optimized for API development."""
        return """# CLAUDE.md - API Development Configuration

## ⚡ Performance Configuration  
- **Execution Mode**: Parallel-first
- **Agent Count**: 5 (backend-dev, api-docs, tester, reviewer, performance-benchmarker)
- **Batch Operations**: MANDATORY
- **Token Optimization**: Level 3 (Aggressive)

## 🎯 Primary Objectives
1. Build RESTful APIs with 100% OpenAPI documentation
2. Implement comprehensive error handling
3. Achieve <100ms response time for all endpoints
4. Maintain 95% test coverage

## 🚀 Execution Rules

### CRITICAL: Concurrency Requirements
```javascript
// ALWAYS execute in single message:
[
  TodoWrite({ todos: [ALL_TASKS] }),
  Task("API Design", "...", "backend-dev"),
  Task("OpenAPI Docs", "...", "api-docs"),
  Task("Test Suite", "...", "tester"),
  Task("Performance", "...", "performance-benchmarker")
]
```

### API Development Workflow
1. **Design Phase**: Create OpenAPI spec first
2. **Implementation**: Use MultiEdit for endpoint creation
3. **Testing**: Parallel test execution
4. **Documentation**: Auto-generate from OpenAPI
5. **Optimization**: Profile and optimize slow endpoints

## 📊 Success Metrics
- Response Time: <100ms (p95)
- Test Coverage: >95%
- Documentation: 100% coverage
- Error Rate: <0.1%
"""
    
    @staticmethod
    def get_ml_pipeline_template() -> str:
        """Get template optimized for ML pipeline development."""
        return """# CLAUDE.md - ML Pipeline Configuration

## 🧠 MLE-STAR Configuration
- **Ensemble Size**: 5 models
- **Coordination**: Mesh topology
- **Voting Strategy**: Weighted consensus
- **Agent Pool**: 8 (ml-developer × 3, researcher × 2, optimizer × 2, tester)

## 🎯 ML Pipeline Objectives
1. Implement ensemble learning with MLE-STAR
2. Achieve >90% model accuracy
3. Optimize training time <30 minutes
4. Implement automated hyperparameter tuning

## 🚀 MLE-STAR Execution Pattern

### Ensemble Coordination
```python
# Initialize MLE-STAR ensemble
mcp__claude-flow__swarm_init({ 
  topology: "mesh", 
  maxAgents: 8,
  mle_star: {
    enabled: true,
    models: ["model1", "model2", "model3", "model4", "model5"],
    consensus: "weighted_voting"
  }
})

# Spawn specialized agents
[
  Task("Data Preprocessing", "...", "ml-developer"),
  Task("Feature Engineering", "...", "ml-developer"),
  Task("Model Training", "...", "ml-developer"),
  Task("Hyperparameter Tuning", "...", "optimizer"),
  Task("Model Evaluation", "...", "tester")
]
```

## 📊 Performance Targets
- Training Time: <30 min
- Model Accuracy: >90%
- Memory Usage: <8GB
- GPU Utilization: >80%
"""
    
    @staticmethod
    def get_performance_optimization_template() -> str:
        """Get template optimized for performance optimization."""
        return """# CLAUDE.md - Performance Optimization Configuration

## ⚡ Performance-First Configuration
- **Execution Mode**: Speed-optimized
- **Agent Count**: 6 (performance-benchmarker × 2, perf-analyzer, optimizer × 2, tester)
- **Topology**: Mesh (optimal for parallel analysis)
- **Optimization Level**: Maximum

## 🎯 Performance Objectives
1. Identify and resolve performance bottlenecks
2. Implement performance budgets and monitoring
3. Achieve target performance metrics
4. Optimize resource utilization

## 🚀 Performance Workflow
1. **Profiling**: Comprehensive performance analysis
2. **Bottleneck Identification**: Parallel analysis execution
3. **Optimization**: Multi-agent optimization strategies
4. **Validation**: Performance regression testing
5. **Monitoring**: Continuous performance tracking

## 📊 Success Metrics
- Performance Score: >0.9
- Bottleneck Resolution: 100%
- Memory Optimization: >20%
- Execution Time: <50% of baseline
"""
    
    @staticmethod
    def get_testing_template() -> str:
        """Get template optimized for testing automation."""
        return """# CLAUDE.md - Testing Automation Configuration

## 🧪 Testing-First Configuration
- **Execution Mode**: Quality-assured
- **Agent Count**: 6 (tester × 3, performance-benchmarker, reviewer × 2)
- **Topology**: Mesh (optimal for parallel testing)
- **Coverage Target**: >95%

## 🎯 Testing Objectives
1. Achieve comprehensive test coverage
2. Implement parallel test execution
3. Build automated quality assurance
4. Optimize test maintenance

## 🚀 Testing Workflow
1. **Test Planning**: Comprehensive test strategy
2. **Implementation**: Parallel test creation
3. **Execution**: Distributed test execution
4. **Reporting**: Automated test reporting
5. **Maintenance**: Continuous test optimization

## 📊 Success Metrics
- Test Coverage: >95%
- Test Execution Time: <5 min
- Test Success Rate: >99%
- Maintenance Overhead: <10%
"""